const { tapdSdk } = require('@opentapd/tplugin-core');
const sdk = require('./sdk');

module.exports.get = async function (data) {
  // console.log(`execute hook.get : ${JSON.stringify(data)}`);
  return sdk.request('/projects/{project_id}/hooks', 'GET', data);
};

module.exports.post = async function (data) {
  // console.log(`execute hook.post : ${JSON.stringify(data)}`);
  data.data.json = {
    ...data.data.json,
    path: '/',
    svn_post_commit_events: '1',
  };

  // delete data.data.json.merge_requests_events
  // delete data.data.json.push_events
  // delete data.data.json.review_events

  return sdk.request('/projects/{project_id}/hooks', 'POST', data);
};

module.exports.put = async function (data) {
  // console.log(`execute hook.put : ${JSON.stringify(data)}`);

  data.data.json = {
    svn_post_commit_events: 1,
    path: '/',
  };
  return sdk.request('/projects/{project_id}/hook/{hook_id}', 'PUT', data);
};

module.exports.delete = async function (data) {
  // console.log(`execute hook.delete : ${JSON.stringify(data)}`);
  return sdk.request('/projects/{project_id}/hooks/{hook_id}', 'DELETE', data);
};

module.exports.adapter = async function (task) {
  console.log('------task: ', task);
  // console.log(`execute hook.adapter : ${JSON.stringify(data)}`);
  const { workspace_id: workspaceId, data, git_app_id: gitAppId, scm_type: scmType } = task;

  const {
    object_kind: objectKind, user_name: userName, project_id: projectId,
    revision, message, files, rep_name: repName, push_timestamp: pushTimestamp, repository } = data;

  const { homepage } = repository;

  if (objectKind !== 'post_commit') {
    return false;
  }

  const commitId = `${projectId}-${revision}`;

  const log = {
    objectKind,
    projectId,
    revision,
    pushTimestamp,
  };

  // console.log(log);

  const filesArr = [];
  files.forEach((element) => {
    if (!element.type) {
      return ;
    }
    filesArr.push(`${element.type} ${element.file}`);
  });

  const commit = {
    workspace_id: workspaceId,
    commit_id: commitId,
    author: userName,
    message,
    files: filesArr,
    repo: repName,
    repo_id: projectId,
    commit_time: convertUtcToBeijing(pushTimestamp),
    repo_url: homepage,
    commit_url: `${homepage}/commit/${revision}`,
    git_app_id: gitAppId,
    git_env: scmType,
    hook_user_name: userName,
  };

  console.log('------*********-------------------commit: ', commit);
  return await tapdSdk.addCodeCommitInfo(commit);
};


function convertUtcToBeijing(utcTime) {
  const utcDate = new Date(utcTime);
  const beijingOffset = 8 * 60 * 60 * 1000; // 北京时间偏移量为8小时
  const beijingTime = new Date(utcDate.getTime() + beijingOffset);
  const beijingTimeString = beijingTime.toISOString().replace('T', ' ')
    .slice(0, 19);
  return beijingTimeString;
}
